package com.ruoyi.framework.web.service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class WeChatUserInfoUtilService {

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取接口调用凭据
     *
     * @param appId
     * @param appSecret
     * @return
     * @throws IOException
     */
    public JSONObject getAccessToken(String appId, String appSecret) {
        String key = CacheConstants.ACCESS_TOKEN_KEY + appId;
        Boolean hasKey = redisCache.hasKey(key);
        JSONObject jsonObject = null;
        if (hasKey) {
            Object cacheObject = redisCache.getCacheObject(key);
            jsonObject = (JSONObject) cacheObject;
            log.info("从Redis获取 接口调用凭据: {}", jsonObject.toJSONString());
        } else {
            String replaceUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            log.info("接口调用凭据请求参数: {}", replaceUrl);
            jsonObject = JSONObject.parseObject(HttpUtils.sendGet(replaceUrl));
            log.info("接口调用凭据响应参数: {}", jsonObject.toJSONString());
            redisCache.setCacheObject(key, jsonObject, 10, TimeUnit.MINUTES);
        }
        return jsonObject;
    }

    /**
     * 获取用户手机号码
     *
     * @param access_token
     * @return
     * @throws IOException
     */
    public JSONObject getPhoneNumber(String code, String access_token) {
        String replaceUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;
        log.info("获取用户手机号码URL: {}", replaceUrl);
        JSONObject param = new JSONObject();
        param.put("code", code);
        log.info("获取用户手机号码请求参数: {}", param.toJSONString());
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.sendPost(replaceUrl, param.toJSONString()));
        log.info("获取用户手机号码: {}", jsonObject.toJSONString());
        return jsonObject;
    }

    /**
     * 获取微信用户信息
     *
     * @param openid
     * @param access_token
     * @return
     */
    public static JSONObject getUserInfo(String openid, String access_token) {
        String replaceUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
        log.info("获取用户请求参数: {}", replaceUrl);
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.sendGet(replaceUrl));
        log.info("获取用户响应参数: {}", jsonObject.toJSONString());
        return jsonObject;
    }
}
